package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dtos.AdminUserDTO;
import com.heima.model.admin.pojos.AdminUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author:Dikk
 * @create: 2023-08-01 09:01
 * @Description: AdminLoginServiceImpl
 */
@Service
@Slf4j
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper, AdminUser> implements AdminLoginService {

    @Autowired
    private AdminLoginMapper adminLoginMapper;

    /**
     * 用户登录
     *
     * @param adminUserDTO
     * @return
     */
    @Override
    public ResponseResult login(AdminUserDTO adminUserDTO) {
        try {
            //参数校验
            if (Objects.isNull(adminUserDTO)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //根据用户名查询用户
            AdminUser adminUser = adminLoginMapper.selectOne(Wrappers.
                    <AdminUser>lambdaQuery().eq(AdminUser::getName, adminUserDTO.getName()));
            //查看用户是否存在
            if (Objects.isNull(adminUser)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //存在 用户输入密码+盐 md5加密
            String userInputPassword = DigestUtils.md5DigestAsHex((adminUserDTO.getPassword()
                    + adminUser.getSalt()).getBytes(StandardCharsets.UTF_8));
            String password = adminUser.getPassword();
            if (!userInputPassword.equals(password)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码正确,允许登录,获取token
            String token = AppJwtUtil.getToken(adminUser.getId().longValue());

            //将得到的token返回给前端数据
            Map<String, Object> resultMap = new HashMap<>();
            adminUser.setPassword("");
            adminUser.setSalt("");
            resultMap.put("token", token);
            resultMap.put("user", adminUser);
            return ResponseResult.okResult(resultMap);
        } catch (Exception e) {
            log.info("登录报错:{}",e);
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_FILED);
        }
    }
}
